<?php
/**
 * 配置模型
 * ===============================================
 * @copyright 深圳市顶速网络科技有限公司  http://fasttop.top
 * ===============================================
 * @author: 小陈先生 <945146147@qq.com>
 * @date: 2015-5-3
 */
namespace Common\Model;
class ConfigModel extends \Think\Model {
	
	protected $_validate = array (
		array ('config_name', 'require', '配置标识名称不能为空', self::EXISTS_VALIDATE, 'regex', self::MODEL_INSERT ), 
		array ('config_name', '', '配置标识名称已存在', self::VALUE_VALIDATE, 'unique', self::MODEL_INSERT ),
		array ('config_title', 'require', '配置标题不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH) 
	);
	
	protected $_auto = array (
		array ('config_name', 'strtoupper', self::MODEL_BOTH, 'function'),
		array ('create_time', NOW_TIME, self::MODEL_INSERT),
		array ('update_time', NOW_TIME, self::MODEL_UPDATE)
	);
	
	public function _initialize() {
	
	}
	
	/**
	 * 获取配置列表
	 * @access public
	 * @return array 配置数组
	 */
	public function getList() {
		$where = array ('status' => 1 );
		$data = $this->where ( $where )->field ( 'config_type,config_name,config_value' )->select ();
		$config = array ();
		if ($data && is_array ( $data )) {
			foreach ( $data as $value ) {
				$config [$value ['config_name']] = $this->_parse ( $value ['config_type'], $value ['config_value'] );
			}
		}
		return $config;
	}
	
	/**
	 * 根据配置类型解析配置
	 * @access private
	 * @param  integer $type  配置类型
	 * @param  string  $value 配置值
	 */
	private function _parse($type, $value) {
		switch ($type) {
			// 解析数组
			case 4 :
				$array = preg_split ( '/[,;\r\n]+/', trim ( $value, ",;\r\n" ) );
				if (strpos ( $value, ':' )) {
					$value = array ();
					foreach ( $array as $val ) {
						list ( $k, $v ) = explode ( ':', $val );
						$value [$k] = $v;
					}
				} else {
					$value = $array;
				}
				break;
		}
		return $value;
	}
	
	/**
	 * 根据配置ID获取配置信息
	 * @param int $id
	 */
	public function getConfigById($id){
		$where ['id'] = $id;
		return $this->where ( $where )->find ();
	}
	
	/**
	 * 根据条件获取执行字段信息
	 * @param string $field
	 * @param array $where
	 * @param string $order
	 */
	public function getConfig($field = '*', $where = array(), $order='sort_order desc'){
		return $this->where ( $where )->field ( $field )->order( $order )->select();
	}
	
	/**
	 * 修改配置信息
	 * @param array $data
	 * @param array $where
	 */
	public function editConfig($data, $where = array()){
		return $this->where ( $where )->save ( $data );
	}
}